import {
    login as loginApi,
    logout as logoutApi
} from '../api/modules/login';
import {
    getCurrentProfile
} from "../api/modules/account"
import LocalStorage from './localStorage'
import {
    TOKEN_EXPIRE_MESSAGE,
    TOKEN_PREFIX,
    TOKEN_KEY
} from '../config';
import {
    promisifyApi
} from './hocks';

// 是否登录开发者服务端
// let isDeveloperServerLogin = false;
// 是否登录抖音主端
let isDouyinLogin = false;
let userInfo;
const duration=30*60*1000;
class LoginController {

    // _openid = '';
    // _unionid = '';

    /**
     * @description: 登录函数，首先调用tt.login获取code，并向开发者服务端请求登录
     * @param {boolean} force 当用户未登录抖音app时，是否强制调起抖音app登录界面
     * @return {boolean}
     */
    async login(force = true) {
        if (LocalStorage.getItem("isDeveloperServerLogin")) {
            return;
        }
        let loginData = null;
        try {
            // 是否强制调起抖音的登录窗口
            loginData = await promisifyApi(tt.login, {
                force
            });
            isDouyinLogin = loginData.isLogin;
        } catch (err) {
            tt.showToast({
                icon: 'fail',
                title: '开发者取消登录抖音',
            });
            throw err;
        }
        if (isDouyinLogin && loginData) {
            try {
                // 与开发者服务端交互，进行登录
                await this.loginToDeveloperServer(loginData.code);
                await this.fetchUserInfo();
                // isDeveloperServerLogin = true;
            } catch (err) {
                tt.showToast({
                    title: '授权登录失败',
                    icon: 'fail',
                });
                throw err;
            }
        }
        return LocalStorage.getItem("isDeveloperServerLogin");
    }

    /**
     * @description: 请求开发者服务端，做code2session
     * @param {string} code tt.login返回的code
     * @return {*}
     */
    async loginToDeveloperServer(code) {
        try {
            // tt.showLoading({
            //     title: ' ',
            // });
            const res = await loginApi({
                code
            });
            // this._token = res.data.token;
            // this._openid = res.data.openid;
            // this._unionid = res.data.unionid;
            LocalStorage.setItem("token", TOKEN_PREFIX + res.data.token, duration)
            LocalStorage.setItem("refreshToken", TOKEN_PREFIX + res.data.refreshToken,duration)
            LocalStorage.setItem("isDeveloperServerLogin", true, duration);
            // tt.setStorageSync('token', TOKEN_PREFIX + res.data.token);
            // tt.setStorageSync('refreshToken', TOKEN_PREFIX + res.data.refreshToken);
            // tt.setStorageSync('openid', res.data.openid);
            // tt.setStorageSync('unionid', res.data.unionid);
        } catch (err) {
            throw err;
        } finally {
            // tt.hideLoading({});
        }
    }
    async fetchUserInfo() {
        const {
            data
        } = await getCurrentProfile();
        LocalStorage.setItem("userInfo",data,duration)
    }
    /**
     * @description: 登出开发者服务端
     * @return {*}
     */
    async logout() {
        // await logoutApi()
        LocalStorage.clear("isDeveloperServerLogin")
        LocalStorage.clear("token")
        LocalStorage.clear("refreshToken")
        LocalStorage.clear("userInfo")
        // isDeveloperServerLogin = false;
        // tt.removeStorageSync('token');
        // tt.removeStorageSync('openid');
        // tt.removeStorageSync('unionid');
        // tt.removeStorageSync('phoneNumberLogin');
        // tt.removeStorageSync('customLogin');
    }

    /**
     * @description: 获取localStorage中的token
     * @return {string}
     */
    getToken() {
        return LocalStorage.getItem('token');
    }
    getUserInfo() {
        return   LocalStorage.getItem("userInfo");
    }
    /**
     * @description: 返回是否登录抖音主端
     * @return {*}
     */
    isDouyinLogin() {
        return isDouyinLogin;
    }

    /**
     * @description: 是否登录开发者服务端
     * @return {*}
     */
    isDeveloperServerLogin() {
        return LocalStorage.getItem("isDeveloperServerLogin") || false;
    }

    // openid和unionid由开发者服务端下发，此处只是为了前端做展示；
    // 在实际情况中不建议开发者下发openid和unionid
    /**
     * @description: 获取localStorage中的openid
     * @return {string}
     */
    getOpenid() {
        return this._openid || tt.getStorageSync('openid');
    }

    /**
     * @description: 获取localStorage中的unionid
     * @return {string}
     */
    getUnionid() {
        return this._unionid || tt.getStorageSync('unionid');
    }
}
export const loginController = new LoginController();